package com.design.pattern.strategy.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.EnumMap;
import java.util.Map;

/**
 * @author goujian
 *
 * @description: 策略的简单工厂
 * @date 2022/3/14 9:57 上午
 */
@Component
public class LoginFactory implements InitializingBean, ApplicationContextAware {
    private static final Map<LoginTypeEnum, LoginStrategy> LOGIN_TYPE_MAP = new EnumMap(LoginTypeEnum.class);
    private ApplicationContext applicationContext;

    public LoginStrategy<LoginReqDto> getLoginBean(LoginTypeEnum loginTypeEnum) {
        return LOGIN_TYPE_MAP.get(loginTypeEnum);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        applicationContext.getBeansOfType(LoginStrategy.class)
                .values()
                .forEach(loginStrategy -> LOGIN_TYPE_MAP.put(loginStrategy.getLoginType(), loginStrategy));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
